var express = require('express');

var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false, limit: '50mb' }));
app.use(express.static(__dirname + '/src'));

app.get('/', function(req, res) {
    res.redirect('/adtopic?car=q50l');
});
  
app.get('/adtopic', function(req, res) {
    var type = req.query.car;
    if(type.trim() == 'q50l'){
        res.sendFile(__dirname + '/views/index.html');
    }
    else if(type.trim() == 'qx60'){
        res.sendFile(__dirname + '/views/qx60.html');
    }
});


app.get('/admin/download', function(req, res) {
    res.sendFile(__dirname + '/views/getfile.html');
});

app.post('/sign_up', function(req, res){
    var ret = {
        error: 0
    }
    var name = req.body.name;
    var phone = req.body.phone;
    var sex = req.body.sex;
    var city = req.body.city;
    var distributor = req.body.distributor;
    var adress = req.body.adress;
    var date = req.body.date;
    var now = formatFullDate(new Date());

    var data = require('./data.json');
    data.push({
        name: name,
        phone: phone,
        sex: sex,
        city: city,
        distributor: distributor,
        adress: adress,
        date: date,
        time: now
    });

    fs.writeFile("./data.json", JSON.stringify(data), function(err) {
        if(err) {
            ret.error = 500;
            ret.msg = '保存失败';
        }
        else{
            ret.msg = '提交成功！10元ETCP停车券将在2个工作日内发放';
        }
        return res.send(JSON.stringify(ret));
    }); 
    
});

app.get('/download', function(req,res){
    var ret = {
        error:0
    }
    var username = req.query.username;
    var passwd = req.query.passwd;
    var config = require('./config');
    var check = false;
    var date = formatDate(new Date());
    var secret = config.secret;
    for(var k in secret){
        if(secret[k].username.toLowerCase() == username.toLowerCase() && 
           secret[k].passwd.toLowerCase()+date == passwd.toLowerCase()){
            check = true;
            break;
        }
    }
    if(!check){
        ret.error = 403;
        ret.msg = '账号密码错误';
        return res.send(JSON.stringify(ret));
    }
    var sheetName = '报名账号信息'+date;
    var cols = config.cols;
    var data = require('./data.json');
    var Excel = require('exceljs');
    var workbook = new Excel.Workbook();
    workbook.creator = 'Administrator';
    workbook.lastModifiedBy = 'Administrator';
    workbook.created = new Date();
    workbook.modified = new Date();
    workbook.lastPrinted = new Date();

    var sheet = workbook.addWorksheet(sheetName);
    var rows = new Array();
    var columns = new Array();
    for(var n in cols){
        columns.push(cols[n]);
    }
    for(var k in data){
        var info = data[k];
        var item = [];
        for(var m in cols){
            item.push(info[m] ? info[m].toString() : '');
        }
        rows.push(item);
    }
    sheet.columns = columns;
    sheet.addRows(rows);
    //workbook.addStyle(sheet);

    workbook.xlsx.writeBuffer().then(function(b){
        res.setHeader('Content-Type', 'application/vnd.openxmlformats');
        res.setHeader("Content-Disposition", "attachment; filename=" + encodeURIComponent(sheetName) + ".xlsx");
        res.end(b, 'binary');
    }).catch(function(err){
        console.log(err);
        ret.error = 500;
        ret.msg = '导出失败';
        return res.send(JSON.stringify(ret));
    });
});

function formatFullDate(date){
    var _time = "";
    if (date != undefined && date != '' && date != "0000-00-00 00:00:00") {
        date = new Date(date);
        _time = date.getFullYear() + "-" + 
        (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-" + 
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())+ " " + 
        (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":" + 
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":" + 
        (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    }
    return _time;
}

function formatDate(date) {
    var _time = "";
    if (date != undefined && date != '' && date != "0000-00-00 00:00:00" && date != "0000-00-00") {
        date = new Date(date);
        _time = date.getFullYear() + "-" + (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + "-" + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    }
    return _time;
}

var port = 8800;
console.log('listening port '+port);
app.listen(port);